//
//  AddressManageViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/9.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "AddressManageViewController.h"
#import "AddAddressViewController.h"
#import "AddressTableViewCell.h"
#import "AddressManagerModel.h"
#import "OrderDetialViewController.h"

@interface AddressManageViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic,strong)  NSMutableArray        * dataArray;
@property (nonatomic,assign)  NSInteger             current_page;
@property (nonatomic,strong)  AddressManagerModel   * addressManagerModel;

@end

@implementation AddressManageViewController

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initViewUI];
    [self setTableViewRefresh];
    
    [self.tableView.mj_header beginRefreshing];
    
    [kNotificationCenter addObserver:self selector:@selector(refreshTableView) name:@"ReloadAddressList" object:nil];
    
}

- (void)initViewUI{
    
    self.title = @"收货地址管理";
    self.view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT) ];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = ScreenX375(108);
    [self.view addSubview:self.tableView];
    
    UIView *operateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(155))];
    self.tableView.tableFooterView = operateView;
    
    OperateButton *button = [[OperateButton alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(50), SCREEN_WIDTH - ScreenX375(26), ScreenX375(44))];
    [button setTitle:@"+ 添加新地址" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(addNew) forControlEvents:UIControlEventTouchUpInside];
    [operateView addSubview:button];
}

- (void)setTableViewRefresh
{
    WeakObj(self);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        selfWeak.current_page = 1;
        [selfWeak requestData];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [selfWeak requestMoreData];
    }];
}


- (void)dealloc {
    [kNotificationCenter removeObserver:self name:@"ReloadAddressList" object:nil];
}

- (void)addNew {
    AddAddressViewController *vc = [[AddAddressViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 刷新数据
- (void)refreshTableView
{
    [self.tableView.mj_header beginRefreshing];
}


-(void)requestData
{
    NSString * url = [NSString stringWithFormat:@"%@app/address_info",REQUESTHEADER];
    NSDictionary * parameter = @{@"token":kNSUDefaultReadKey(@"token"),@"page":@1};
    [HttpManager showWait];
    [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
        [HttpManager hideWait];
        [self.tableView.mj_header endRefreshing];
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        
        if ([status isEqualToString:@"1"]) {
            NSError *error;
            // 成功
            NSDictionary *dict = successResponse;
            AddressManagerModel *addressModel = [[AddressManagerModel alloc] initWithDictionary:dict[@"data"] error:&error];
            self.addressManagerModel = addressModel;
            if (addressModel != nil) {
                [self.dataArray removeAllObjects];
                self.dataArray = [self.addressManagerModel.data mutableCopy];
                [self.tableView reloadData];
            }
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [self.tableView.mj_header endRefreshing];
        [HttpManager showFail];
    }];
}

-(void)requestMoreData
{
    self.current_page ++;
    NSString * url = [NSString stringWithFormat:@"%@app/address_info",REQUESTHEADER];
    NSDictionary * parameter = @{@"token":kNSUDefaultReadKey(@"token"),@"page":@(self.current_page)};
    [HttpManager showWait];
    [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
        [HttpManager hideWait];
        [self.tableView.mj_footer endRefreshing];
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        
        if ([status isEqualToString:@"1"]) {
            NSError *error;
            self.current_page = [successResponse[@"data"][@"last_page"] integerValue];
            // 成功
            NSDictionary *dict = successResponse;
            AddressManagerModel *addressModel = [[AddressManagerModel alloc] initWithDictionary:dict[@"data"] error:&error];
            self.addressManagerModel = addressModel;
            if (addressModel != nil) {
                self.dataArray = [[self.dataArray arrayByAddingObjectsFromArray:self.addressManagerModel.data] mutableCopy];
                [self.tableView reloadData];
            }
 
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [self.tableView.mj_footer endRefreshing];
        [HttpManager showFail];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressManagerDataModel *model = self.dataArray[indexPath.section];
    AddressTableViewCell *cell = [AddressTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
    
    WeakObj(self);
    cell.editClick = ^{
        AddAddressViewController *vc = [[AddAddressViewController alloc] init];
        vc.addressModel = model;
        [selfWeak.navigationController pushViewController:vc animated:YES];
    };
    cell.selectClick = ^{
        NSString * url = [NSString stringWithFormat:@"%@app/address_default",REQUESTHEADER];
        NSDictionary * parameter = @{@"token":[FPLoginAndRegisterTools getToken],@"address_id":model.Id};
        [HttpManager showWait];
        [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
            
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [HttpManager showNoteMsg:@"设置成功"];
                [selfWeak.tableView.mj_header beginRefreshing];
            }else{
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    };
    cell.deleteClick = ^{
        NSString * url = [NSString stringWithFormat:@"%@app/address_delete",REQUESTHEADER];
        NSDictionary * parameter = @{@"token":[FPLoginAndRegisterTools getToken],@"address_id":model.Id};
        [HttpManager showWait];
        [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [HttpManager showNoteMsg:@"删除成功"];
                [selfWeak.dataArray removeObjectAtIndex:indexPath.row];
                [selfWeak.tableView reloadData];
            }else{
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    };
    cell.addressDataModel = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return ScreenX375(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
    view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isSelect) {
        AddressManagerDataModel *model = [self.dataArray objectAtIndex:indexPath.section];
        [_delegate passValue:model];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
